package com.yeepay.challenge.game2048.chenpeng;

import com.yeepay.challenge.game2048.GamePlayer;
import com.yeepay.challenge.game2048.chenpeng.ai.MonteCarloAI;
import com.yeepay.challenge.game2048.chenpeng.model.Direction;
import com.yeepay.challenge.game2048.chenpeng.model.TwentyFortyEightGame;

/**
 * 2014年12月24日 18:31:28
 * @author Chen
 *
 */
public class PlayerImpl implements GamePlayer {

	@Override
	public String play(int[][] gameData) {
		TwentyFortyEightGame currentGame = new TwentyFortyEightGame(gameData);
		MonteCarloAI m = new MonteCarloAI(currentGame);
		Direction d = m.getBestDirection(Client.depth);
		String direciton = "";
		if (d != null) {
			switch (d) {
			case UP:
				direciton = "U";
				break;
			case DOWN:
				direciton = "D";
				break;
			case LEFT:
				direciton = "L";
				break;
			case RIGHT:
				direciton = "R";
				break;
			default:
				break;
			}
		} else {
			showGameData(gameData);
			direciton = "U";
		}
		return direciton;
	}


	/**
	 * 展示网格
	 * 
	 * @param gameData
	 */
	private void showGameData(int[][] grid) {
		// for (int[] is : grid) {
		// for (int i : is) {
		// System.out.print(i + "\t");
		// }
		// System.out.println();
		// }
		String s = "";
		s += "+=====+=====+=====+=====+\n";
		int size = 4;
		for (int row = 0; row < size; row++) {
			s += "|";
			for (int col = 0; col < size; col++) {
				int tile = grid[row][col];

				int space = 5 - getNumDigit(tile);
				String spaceString = "";
				for (int i = 0; i < space; i++)
					spaceString += " ";

				s += tile == 0 ? " " : tile;
				s += spaceString;
				s += "|";
			}
			s += "\n+=====+=====+=====+=====+\n";
		}
		System.out.print(s);
	}

	/**
	 * 计算空格余量
	 * 
	 * @param num
	 * @return
	 */
	private int getNumDigit(int num) {
		if (num < 10)
			return 1;
		else
			return getNumDigit(num / 10) + 1;
	}

}
